package org.gitman.agent.platform;

import com.mxgraph.model.mxICell;
import com.mxgraph.model.mxIGraphModel;
import com.mxgraph.util.mxConstants;
import com.mxgraph.util.mxUtils;
import com.mxgraph.view.mxGraph;

public class GraphSimmulationViewer {
	
	private Simulation simulation;
	private mxGraph graph;
	private AgentManager agentManager;

	public GraphSimmulationViewer(Simulation simulation){
		this.simulation = simulation;
	}
	
	public void init(mxGraph graph){
		this.graph = graph;
		agentManager = simulation.getAgentManager();
		Object [] cells = graph.getChildCells(graph.getDefaultParent());
		graph.setCellStyles(mxConstants.STYLE_FILLCOLOR, null, cells);
		
		for(Agent agent : agentManager.getAllAgentsInQueue()){
			moveAgent(agent, agent.getStartPoint(), agent.getCurrentPoint());
		}
	}
	
	public void moveAgent(Agent agent, mxICell from, mxICell to){
		mxIGraphModel model = graph.getModel();
		model.beginUpdate();
		try{
			graph.setCellStyles(mxConstants.STYLE_FILLCOLOR, null, new Object[]{from});
			graph.setCellStyles(mxConstants.STYLE_FILLCOLOR, mxUtils.getHexColorString(agent.getColor()), new Object[]{to});
		}finally{
			model.endUpdate();
		}
	}

	public void agentFinished(Agent agent){
		mxIGraphModel model = graph.getModel();
		mxICell point = agent.getCurrentPoint();
		model.beginUpdate();
		try{
			graph.setCellStyles(mxConstants.STYLE_FILLCOLOR, null, new Object[]{point});
		}finally{
			model.endUpdate();
		}
	}
}
